<template>
  <view class="create-task-container">
    <!-- 基础信息 -->
    <view class="section">
      <view class="section-title">基础信息</view>
      <view class="section-nr">
          <!-- 供应商 -->
        <view class="form-item">
          <text class="label">供应商：</text>
          <view class="picker-content">
            <text class="picker-text">{{ supplierOptions[supplierIndex] || '暂无供应商' }}</text>
          </view>
        </view>
        
   <!-- 单据类型 -->
      <view class="form-item">
        <text class="label">单据类型：</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="taskTypeOptions" 
          @change="onTaskTypeChange"
          :value="taskTypeIndex"
        >
          <view class="picker-content">
            <text class="picker-text">{{ taskTypeOptions[taskTypeIndex] || '请选择任务类型' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      



      <!-- 送货司机 -->
      <view class="form-item">
        <text class="label">送货司机：</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="loadingDriverOptions" 
          @change="onLoadingDriverChange"
          :value="loadingDriverIndex"
        >
          <view class="picker-content">
            <text class="picker-text">{{ loadingDriverOptions[loadingDriverIndex] || '请选择送货司机' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>


      <!-- 送货车辆 -->
      <view class="form-item">
        <text class="label">送货车辆：</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="loadingVehicleOptions" 
          @change="onLoadingVehicleChange"
          :value="loadingVehicleIndex"
        >
          <view class="picker-content">
            <text class="picker-text">{{ loadingVehicleOptions[loadingVehicleIndex] || '请选择送货车辆' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <!-- 备注 -->
      <view class="form-item">
        <text class="label">备注：</text>
        <input 
          class="input" 
          type="text" 
          placeholder="请输入" 
          v-model="remark"
        />
      </view>
      </view>
   
    </view>
    
    <!-- 商品信息 -->
    <view class="section">
      <view class="section-title">
        <text>商品信息</text>
        <text 
          class="add-product-btn" 
          @click="handleAddProduct"
          :class="{ 'add-product-btn-disabled': supplierIndex === '' }"
        >添加商品</text>
      </view>
      
      <!-- 商品列表为空时的提示 -->
      <view class="empty-products" v-if="productList.length === 0">
        <text class="empty-text">当前无商品，请添加商品</text>
      </view>
      
      <!-- 商品列表 -->
       <view class="product-list" v-else>
        <!-- 商品卡片 -->
        <view 
          class="product-card" 
          v-for="(product, index) in productList" 
          :key="product.rowid"
        >
          <!-- 商品图片 -->
          <view class="product-image">
            <image 
              :src="getFirstImage(product['6864930a4e2949f411990010'])" 
              mode="aspectFill"
              class="image"
            ></image>
          </view>
          
          <!-- 描述区域 -->
          <view class="product-info">
            <text class="product-name">{{ product['68634c1c87058ae1c65da306'] }}</text>
            <text class="product-code">商品条码：{{ product['68634c1c87058ae1c65da312'] }}</text>
            
            <!-- 计划入库数量输入 -->
            <view class="quantity-input-wrapper">
              <text class="quantity-label">计划入库数量：</text>
              <input 
                class="quantity-input" 
                type="number" 
                placeholder="请输入数量" 
                v-model="product.plannedQuantity"
                @input="validateQuantity(product)"
              />
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="product-actions">
            <button class="delete-btn" @click="handleDeleteProduct(index)">删除</button>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="productList.length === 0">
          <text class="empty-text">暂无商品数据</text>
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-actions">
      <button 
        class="save-btn" 
        :class="{ 'save-btn-disabled': isSaveDisabled }"
        :disabled="isSaveDisabled"
        @click="handleSave"
      >
        保存任务
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch} from 'vue'
import http from '../../../utils/request'
import { useUserStore } from '../../../store/user'
import { useTaskStore } from '../../../store/task'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { callWorkflowListAPI, callWorkflowAPI } from '../../../utils/workflow'

const userStore = useUserStore()
const taskStore = useTaskStore()

// 任务类型选项
const taskTypeOptions = ref(['到货入库', '多余退货', '客退入库'])
const taskTypeIndex = ref('')



// 供应商选项
const supplierOptions = ref([])
const supplierIndex = ref('')
const supplierData = ref([]) // 供应商完整数据
const supplierRowid = ref('') // 选择的供应商rowid

// 送货司机选项
const loadingDriverOptions = ref([])
const loadingDriverIndex = ref('')

// 送货车辆选项
const loadingVehicleOptions = ref([])
const loadingVehicleIndex = ref('')

// 备注
const remark = ref('')

// 商品列表
const productList = ref([])




// 计算属性：保存按钮是否应该禁用
const isSaveDisabled = computed(() => {
  // 任务类型未选择
  if (taskTypeIndex.value === '') {
    return true
  }
  
  // 供应商未选择
  if (supplierIndex.value === '') {
    return true
  }
  
  // 商品列表为空
  if (productList.value.length === 0) {
    return true
  }
  
  // 检查所有商品是否都有计划入库数量
  for (let i = 0; i < productList.value.length; i++) {
    const product = productList.value[i]
    if (!product.plannedQuantity || product.plannedQuantity.trim() === '') {
      return true
    }
  }
  
  return false
})

// 处理任务类型选择变化
const onTaskTypeChange = (e) => {
  taskTypeIndex.value = e.detail.value
}





// 处理供应商选择变化
const onSupplierChange = (e) => {
  supplierIndex.value = e.detail.value
  
  // 设置选择的供应商rowid
  if (supplierIndex.value !== '' && supplierData.value[supplierIndex.value]) {
    supplierRowid.value = supplierData.value[supplierIndex.value].rowid
    console.log('设置供应商rowid:', supplierRowid.value)
  } else {
    supplierRowid.value = ''
  }
}

// 处理送货司机选择变化
const onLoadingDriverChange = (e) => {
  loadingDriverIndex.value = e.detail.value
}

// 处理送货车辆选择变化
const onLoadingVehicleChange = (e) => {
  loadingVehicleIndex.value = e.detail.value
}

// 处理添加商品
const handleAddProduct = () => {
  // 检查是否选择了供应商
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请先选择供应商',
      icon: 'none'
    })
    return
  }
  
  // 获取当前选择的供应商名称
  const supplierName = supplierOptions.value[supplierIndex.value]
  
  uni.navigateTo({
    url: `/pages/warehouse/inbound/add-product?supplierName=${encodeURIComponent(supplierName)}&supplierRowid=${encodeURIComponent(supplierRowid.value)}`
  })
}

// 接收从添加商品页面返回的选中商品
const receiveSelectedProducts = (selectedProducts) => {
  // 将选中的商品添加到商品列表中
  selectedProducts.forEach(product => {
    // 检查是否已存在相同商品，避免重复添加
    const existingIndex = productList.value.findIndex(item => item.rowid === product.rowid)
    if (existingIndex === -1) {
      // 添加新商品到列表，包含计划入库数量字段
      productList.value.push({
        rowid: product.rowid,
        '68634c1c87058ae1c65da306': product['68634c1c87058ae1c65da306'], // 商品名称
        '68634c1c87058ae1c65da312': product['68634c1c87058ae1c65da312'], // 商品条码
        '6864930a4e2949f411990010': product['6864930a4e2949f411990010'], // 商品图片
        plannedQuantity: '' // 计划入库数量，初始为空
      })
    }
  })
}

// 处理删除商品
const handleDeleteProduct = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该商品吗？',
    success: (res) => {
      if (res.confirm) {
        productList.value.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 验证商品数量
const validateQuantity = (product) => {
  // 确保数量是有效的正整数
  if (product.plannedQuantity) {
    const quantity = parseInt(product.plannedQuantity)
    if (isNaN(quantity) || quantity <= 0) {
      product.plannedQuantity = ''
      uni.showToast({
        title: '请输入有效的数量',
        icon: 'none'
      })
    } else {
      product.plannedQuantity = quantity.toString()
    }
  }
}

// 检查所有商品是否都有计划入库数量
const checkAllProductsHaveQuantity = () => {
  for (let i = 0; i < productList.value.length; i++) {
    const product = productList.value[i]
    if (!product.plannedQuantity || product.plannedQuantity.trim() === '') {
      uni.showToast({
        title: `请填写第${i + 1}个商品的计划入库数量`,
        icon: 'none'
      })
      return false
    }
  }
  return true
}

// 处理保存任务
const handleSave = async () => {
  // 如果按钮被禁用，直接返回
  if (isSaveDisabled.value) {
    return
  }
  
  // 表单验证
  if (taskTypeIndex.value === '') {
    uni.showToast({
      title: '请选择任务类型',
      icon: 'none'
    })
    return
  }
  
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请选择供应商',
      icon: 'none'
    })
    return
  }
  
  // 根据任务类型进行相应的验证
  const selectedType = taskTypeOptions.value[taskTypeIndex.value]
  
  if (productList.value.length === 0) {
    uni.showToast({
      title: '请添加商品信息',
      icon: 'none'
    })
    return
  }
  
  // 验证所有商品都有计划入库数量
  if (!checkAllProductsHaveQuantity()) {
    return
  }

  // 打印表单数据
  const formData = {
    userRowid: userStore.getUserInfo().rowid,
    warehouseCode: userStore.warehouseCode,
    taskType: selectedType,

    supplier: supplierIndex.value !== '' ? supplierOptions.value[supplierIndex.value] : '',
    loadingDriver: loadingDriverIndex.value !== '' ? loadingDriverOptions.value[loadingDriverIndex.value] : '',
    loadingVehicle: loadingVehicleIndex.value !== '' ? loadingVehicleOptions.value[loadingVehicleIndex.value] : '',
    remark: remark.value,
    products: productList.value.map(product =>{
      return  {
        rowid: product.rowid,
        plannedQuantity: product.plannedQuantity || '0'
      }
    })
  }

  await http.post(`https://www.dachen.vip/api/workflow/hooks/${userStore.getWarehouseInfo().gys_rk_create}`, formData)
  
  console.log('保存的表单数据:', formData)
  
  // 保存逻辑
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })

taskStore.setPendingTaskUpdate({
  updata: "updata"
})
  
  // 返回上一页
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

// 获取第一张图片
const getFirstImage = (imageData) => {
  if (!imageData) return ''
  
  try {
    // 如果已经是字符串数组，直接返回第一个
    if (Array.isArray(imageData)) {
      return imageData[0] || ''
    }
    
    // 如果是JSON字符串，解析后取第一个图片的thumbnail_full_path
    const parsedData = JSON.parse(imageData)
    if (Array.isArray(parsedData) && parsedData.length > 0) {
      return parsedData[0].thumbnail_full_path || parsedData[0].file_path || ''
    }
  } catch (error) {
    console.error('解析图片数据失败:', error)
  }
  
  return ''
}

// 获取供应商
const getSupplier = async () => {
  try {
      const res = await callWorkflowListAPI('gonghuoshang')
  if(res){
    console.log('供应商', res.data);
    // 过滤供应商数据
    const filteredSuppliers = res.data.filter(item => {
      try {
       return JSON.parse(userStore.getUserInfo()['68ea18b6470b6cef2f580870']).includes(item.rowid)
      } catch (error) {
        console.log('解析供应商数据失败:', error);
        return false;
      }
    })
    
    // 保存完整的供应商数据
    supplierData.value = filteredSuppliers
    
    // 提取供应商名称
    supplierOptions.value = filteredSuppliers.map(item => {
      return item['68639102a4471151d6aaa98b']
    })
    
    // 自动设置第一个供应商
    if (filteredSuppliers.length > 0) {
      supplierIndex.value = 0
      supplierRowid.value = filteredSuppliers[0].rowid
      console.log('自动设置第一个供应商:', supplierOptions.value[0], 'rowid:', supplierRowid.value)
    }
    
  }
  } catch (error) {
    console.error('获取供应商失败:', error)
  }
  
}



// 获取送货司机
const getLoadingDriver = async () => {
  try {
      const res = await callWorkflowListAPI('sjgl')
  if(res){
    console.log('送货司机', res.data);
    loadingDriverOptions.value = res.data.map(item => {
      return item['686500504e2949f4119926d4']
    })
    
  }
  } catch (error) {
    console.error('获取送货司机失败:', error)
  }
  
}

// 获取送货车辆
const getLoadingVehicle = async () => {
  try {
      const res = await callWorkflowListAPI('clgl')
  if(res){
    console.log('送货车辆', res.data);
    loadingVehicleOptions.value = res.data.map(item => {
      return item['686500b14e2949f4119926f9']
    })
    
  }
  } catch (error) {
    console.error('获取送货车辆失败:', error)
  }
  
}



// 监听任务更新
watch(() => taskStore.pendingTaskUpdate, async (newTask) => {
  if (newTask) {
    console.log('检测到待更新任务:', newTask)
    productList.value = newTask

    }
      taskStore.clearPendingTaskUpdate()
})

onLoad(async () => {
  uni.showLoading({
    title: '加载中'
  })
  await getSupplier()
  await getLoadingDriver()
  await getLoadingVehicle()
  uni.hideLoading()
})



</script>

<style lang="scss" scoped>
.create-task-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  
  .section {
    margin-bottom: 20rpx;
    
    .section-title {
      padding: 30rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .add-product-btn {
        color: #87CEEB;
        border: none;
        font-size: 28rpx;
        
        &.add-product-btn-disabled {
          color: #cccccc;
          pointer-events: none;
        }
      }
    }

    .section-nr{
        background-color: #ffffff;
        border-radius: 10rpx;
        padding: 10rpx;
        margin: 10px;
   .form-item {
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      align-items: center;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: #333333;
        font-size: 28rpx;
        min-width: 140rpx;
      }
      
      .picker {
        flex: 1;
        
        .picker-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .picker-text {
            color: #333333;
            font-size: 28rpx;
          }
          
          .picker-arrow {
            color: #999999;
            font-size: 24rpx;
          }
        }
      }
      
      .input {
        flex: 1;
        color: #333333;
        font-size: 28rpx;
        
        &::placeholder {
          color: #999999;
        }
      }
    }
    }
    
 
    
    .empty-products {
      padding: 60rpx 30rpx;
      text-align: center;
      
      .empty-text {
        color: #999999;
        font-size: 28rpx;
      }
    }
    
    .product-list {
      padding: 20rpx 30rpx;
      
      .product-card {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
        
        .product-image {
          width: 120rpx;
          height: 120rpx;
          margin-right: 30rpx;
          flex-shrink: 0;
          
          .image {
            width: 100%;
            height: 100%;
            border-radius: 12rpx;
            object-fit: cover;
          }
        }
        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 12rpx;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .product-code {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .quantity-input-wrapper {
            display: flex;
            align-items: center;
            margin-top: 16rpx;
            
            .quantity-label {
              font-size: 24rpx;
              color: #333333;
              margin-right: 16rpx;
              white-space: nowrap;
            }
            
            .quantity-input {
              flex: 1;
              padding: 8rpx 16rpx;
              border: 2rpx solid #e0e0e0;
              border-radius: 8rpx;
              font-size: 24rpx;
              color: #333333;
              min-width: 120rpx;
              
              &::placeholder {
                color: #999999;
              }
              
              &:focus {
                border-color: #0fcee9;
                outline: none;
              }
            }
          }
          
          .product-spec {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .stock-info {
            display: flex;
            flex-direction: column;
            
            .unavailable-stock {
              color: #ff4757;
              font-size: 24rpx;
              margin-bottom: 4rpx;
            }
            
            .available-stock {
              color: #2ed573;
              font-size: 24rpx;
            }
          }
        }
        
        .product-actions {
          display: flex;
          flex-direction: column;
          gap: 16rpx;
          
          .delete-btn {
            padding: 10rpx 20rpx;
            border-radius: 8rpx;
            font-size: 24rpx;
            border: none;
            min-width: 80rpx;
            background-color: #ff4757;
            color: #ffffff;
          }
        }
      }
      
      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999999;
          font-size: 28rpx;
        }
      }
    }
  }
  
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 30rpx;
    box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.1);
    
    .save-btn {
      width: 100%;
      background: linear-gradient(to right, #48eceb, #0fcee9);
      color: #ffffff;
      border: none;
      border-radius: 32rpx;
      font-size: 32rpx;
      font-weight: bold;
      
      &.save-btn-disabled {
        background: #cccccc !important;
        color: #999999 !important;
        cursor: not-allowed;
        opacity: 0.6;
      }
    }
  }
}
</style>